package com.dianrui.fmi.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.dianrui.fmi.R;
import com.dianrui.fmi.adapter.TransactionQuotesAdapter;
import com.dianrui.fmi.bean.Qutos;
import com.dianrui.fmi.event.RfreshSimulatedPage;
import com.dianrui.fmi.fragment.FragmentPostion;
import com.dianrui.fmi.fragment.FragmentSettlements;
import com.dianrui.fmi.util.CountDownTimerUtils;
import com.dianrui.fmi.util.OkHttpUtils;
import com.dianrui.fmi.util.StringUtils;
import com.dianrui.fmi.util.Url;
import com.google.gson.JsonObject;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;

public class SimulatedTransactionNewActivity extends BaseActivity {
    private ProgressDialog pd;
    private List<Fragment> fragments;
    private List<String> titles;
    public static String fragemntPosition;
    private String type = "1";
    private String pageType,pageBack;
    private List<Qutos> mQutoList = new ArrayList<>();
    private TransactionQuotesAdapter quotesAdapter;


    @BindView(R.id.forex_txt)
    TextView forexTxt;
    @BindView(R.id.main_money_line)
    View mainMoneyLine;
    @BindView(R.id.quotes_commoities_txt)
    TextView quotesCommoitiesTxt;
    @BindView(R.id.main_shop_line)
    View mainShopLine;
    @BindView(R.id.quotes_list)
    ListView quotesList;

    @BindView(R.id.transaction_layouts)
    LinearLayout transactionLayouts;
    @BindView(R.id.pager)
    ViewPager pager;


    @BindView(R.id.tablayout)
    TabLayout tablayout;

    @BindView(R.id.transaction_btn)
    Button transactionBtn;

    @BindView(R.id.position_btn)
    Button positionBtn;




    @Override
    public int getContentViewId() {
        return R.layout.activity_simulated_transactions;
    }

    @Override
    public void initView() {
        pd=new ProgressDialog(SimulatedTransactionNewActivity.this);
        if (getIntent() != null && getIntent().getExtras() != null) {
            pageType=getIntent().getStringExtra("pageType");
            pageBack=getIntent().getStringExtra("pageback");
        }
        if (pageType.equals("1")) {
            transactionBtn.setBackgroundResource(R.mipmap.transaction_left_bg);
            transactionBtn.setTextColor(getResources().getColor(R.color.red_deep));
            positionBtn.setTextColor(getResources().getColor(R.color.white));
            positionBtn.setBackgroundResource(R.mipmap.position_right_bg);
            tablayout.setVisibility(View.GONE);
            pager.setVisibility(View.GONE);
            transactionLayouts.setVisibility(View.VISIBLE);
        }else if (pageType.equals("2")) {
            transactionBtn.setBackgroundResource(R.mipmap.transaction_left_bg_unseleted);
            transactionBtn.setTextColor(getResources().getColor(R.color.white));
            positionBtn.setTextColor(getResources().getColor(R.color.red_deep));
            positionBtn.setBackgroundResource(R.mipmap.position_right_bg_selected);
            tablayout.setVisibility(View.VISIBLE);
            pager.setVisibility(View.VISIBLE);
            transactionLayouts.setVisibility(View.GONE);
        }
        quotesAdapter = new TransactionQuotesAdapter(SimulatedTransactionNewActivity.this, mQutoList);
        quotesList.setAdapter(quotesAdapter);
        type="2";
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                getQutosList("2");
            }
        },1000);
        quotesAdapter.setOnButtonClickListener(new TransactionQuotesAdapter.QuotesClickListener() {
            @Override
            public void onRegularClick(long tick,String name, String symbold, String type, String symbol, String fullsymbol, String price, String high, String low, String open, String zf, String yc, String buy1, String buy2, String position, String servicecharge,String zc) {
                Intent intent = new Intent(SimulatedTransactionNewActivity.this, KLineActivity.class);
                Bundle bundle = new Bundle();
                bundle.putLong("tick", tick);
                bundle.putString("symbold", symbold);
                bundle.putString("name", name);
                bundle.putString("type", type);
                bundle.putString("symbol", symbol);
                bundle.putString("open", open);
                bundle.putString("high", high);
                bundle.putString("low", low);
                bundle.putString("fullsymbol", fullsymbol);
                bundle.putString("price", price);
                bundle.putString("zf", zf);
                bundle.putString("zc", zc);
                bundle.putString("yc", yc);
                bundle.putString("type", "2");//购买类型：1实盘，2模拟盘
                bundle.putString("buy1", buy1);
                bundle.putString("buy2", buy2);
                bundle.putString("position", position);
                bundle.putString("servicecharge", servicecharge);
                intent.putExtras(bundle);
                startActivity(intent);
            }

        });
        titles = new ArrayList<>();
        titles.add(getString(R.string.postion_title));
        titles.add(getString(R.string.settlement_title));


        fragments = new ArrayList<>();
        fragments.add(new FragmentPostion());
        fragments.add(new FragmentSettlements());
        //预加载
        pager.setOffscreenPageLimit(fragments.size());

        //设置适配器
        pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            //选中的ITem
            @Override
            public Fragment getItem(int i) {
                return fragments.get(i);
            }

            //返回Item个数
            @Override
            public int getCount() {
                return fragments.size();
            }
            //设置标题

            @Override
            public CharSequence getPageTitle(int position) {
                return titles.get(position);
            }
        });

        tablayout.setupWithViewPager(pager);

        tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 1) {
                    EventBus.getDefault().post(new RfreshSimulatedPage("3"));
                }
                pager.setCurrentItem(tab.getPosition());

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

        pager.setOffscreenPageLimit(2);

        detailsTimer.start();
    }

    CountDownTimerUtils detailsTimer=new CountDownTimerUtils(Long.MAX_VALUE,15000) {
        @Override
        public void onTick(long millisUntilFinished) {
          if (type.equals("2")) {
              getTimerQutosList("2");
            }else  if (type.equals("3")) {
              getTimerQutosList("3");
            }

        }

        @Override
        public void onFinish() {

        }
    };


    @OnClick({R.id.back,R.id.forex_layout, R.id.quotes_commoities_layout, R.id.transaction_btn, R.id.position_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                if (detailsTimer != null) {
                    detailsTimer.cancel();
                }
                finish();
                break;
            case R.id.transaction_btn:
                transactionBtn.setBackgroundResource(R.mipmap.transaction_left_bg);
                transactionBtn.setTextColor(getResources().getColor(R.color.red_deep));
                positionBtn.setTextColor(getResources().getColor(R.color.white));
                positionBtn.setBackgroundResource(R.mipmap.position_right_bg);
                tablayout.setVisibility(View.GONE);
                pager.setVisibility(View.GONE);
                transactionLayouts.setVisibility(View.VISIBLE);
                break;
            case R.id.position_btn:
                transactionBtn.setBackgroundResource(R.mipmap.transaction_left_bg_unseleted);
                transactionBtn.setTextColor(getResources().getColor(R.color.white));
                positionBtn.setTextColor(getResources().getColor(R.color.red_deep));
                positionBtn.setBackgroundResource(R.mipmap.position_right_bg_selected);
                tablayout.setVisibility(View.VISIBLE);
                pager.setVisibility(View.VISIBLE);
                transactionLayouts.setVisibility(View.GONE);
                break;
            case R.id.forex_layout:
                forexTxt.setTextColor(ContextCompat.getColor(SimulatedTransactionNewActivity.this, R.color.orange));
                quotesCommoitiesTxt.setTextColor(ContextCompat.getColor(SimulatedTransactionNewActivity.this, R.color.black_333333));
                mainMoneyLine.setVisibility(View.VISIBLE);
                mainShopLine.setVisibility(View.INVISIBLE);
                type = "2";
                getQutosList("2");
                break;
            case R.id.quotes_commoities_layout:
                forexTxt.setTextColor(ContextCompat.getColor(SimulatedTransactionNewActivity.this, R.color.black_333333));
                quotesCommoitiesTxt.setTextColor(ContextCompat.getColor(SimulatedTransactionNewActivity.this, R.color.orange));
                mainMoneyLine.setVisibility(View.INVISIBLE);
                mainShopLine.setVisibility(View.VISIBLE);
                type = "3";
                getQutosList("3");
                break;
                default:
                    break;

        }
    }

    private void getQutosList(String type) {
        pd.show();
        pd.setMessage(getString(R.string.load));
        pd.setCanceledOnTouchOutside(false);
        pd.setCancelable(false);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("type", type);
        jsonObject.addProperty("is_real", "2");
        OkHttpUtils.getInstance().postWithMemberToken(Url.QUOTES_LIST, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                pd.dismiss();
                                if (mQutoList != null) {
                                    mQutoList.clear();
                                }
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (null != jsonArray && jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        Qutos Qutos = new Qutos();
                                        Qutos.symbols_id = jsonArray.optJSONObject(i).optString("symbols_id");
                                        Qutos.full_symbol = jsonArray.optJSONObject(i).optString("full_symbol");
                                        Qutos.symbol = jsonArray.optJSONObject(i).optString("symbol");
                                        Qutos.name = jsonArray.optJSONObject(i).optString("name");
                                        Qutos.type = jsonArray.optJSONObject(i).optString("type");
                                        Qutos.market = jsonArray.optJSONObject(i).optString("market");
                                        Qutos.tick = jsonArray.optJSONObject(i).optLong("tick");
                                        Qutos.i = jsonArray.optJSONObject(i).optString("i");
                                        Qutos.itd = jsonArray.optJSONObject(i).optString("itd");
                                        Qutos.price = jsonArray.optJSONObject(i).optString("price");
                                        Qutos.o = jsonArray.optJSONObject(i).optString("o");
                                        Qutos.h = jsonArray.optJSONObject(i).optString("h");
                                        Qutos.l = jsonArray.optJSONObject(i).optString("l");
                                        Qutos.yc = jsonArray.optJSONObject(i).optString("yc");
                                        Qutos.v = jsonArray.optJSONObject(i).optString("v");
                                        Qutos.zf = jsonArray.optJSONObject(i).optString("zf");
                                        Qutos.zd = jsonArray.optJSONObject(i).optString("zd");
                                        Qutos.buy1 = jsonArray.optJSONObject(i).optString("buy1");
                                        Qutos.buy2 = jsonArray.optJSONObject(i).optString("buy2");
                                        Qutos.position = jsonArray.optJSONObject(i).optString("position");
                                        Qutos.service_charge = jsonArray.optJSONObject(i).optString("service_charge");
                                        mQutoList.add(Qutos);
                                    }
                                    if (quotesAdapter != null) {
                                        quotesAdapter.refresh(mQutoList);
                                    }

                                }else {
                                    pd.dismiss();
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }else{
                    pd.dismiss();
                }
            }
        });
    }


    private void getTimerQutosList(String type) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("type", type);
        jsonObject.addProperty("is_real", "2");
        OkHttpUtils.getInstance().postWithMemberToken(Url.QUOTES_LIST, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                if (mQutoList != null) {
                                    mQutoList.clear();
                                }
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (null != jsonArray && jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        Qutos Qutos = new Qutos();
                                        Qutos.symbols_id = jsonArray.optJSONObject(i).optString("symbols_id");
                                        Qutos.full_symbol = jsonArray.optJSONObject(i).optString("full_symbol");
                                        Qutos.symbol = jsonArray.optJSONObject(i).optString("symbol");
                                        Qutos.name = jsonArray.optJSONObject(i).optString("name");
                                        Qutos.type = jsonArray.optJSONObject(i).optString("type");
                                        Qutos.market = jsonArray.optJSONObject(i).optString("market");
                                        Qutos.tick = jsonArray.optJSONObject(i).optLong("tick");
                                        Qutos.i = jsonArray.optJSONObject(i).optString("i");
                                        Qutos.itd = jsonArray.optJSONObject(i).optString("itd");
                                        Qutos.price = jsonArray.optJSONObject(i).optString("price");
                                        Qutos.o = jsonArray.optJSONObject(i).optString("o");
                                        Qutos.h = jsonArray.optJSONObject(i).optString("h");
                                        Qutos.l = jsonArray.optJSONObject(i).optString("l");
                                        Qutos.yc = jsonArray.optJSONObject(i).optString("yc");
                                        Qutos.v = jsonArray.optJSONObject(i).optString("v");
                                        Qutos.zf = jsonArray.optJSONObject(i).optString("zf");
                                        Qutos.zd = jsonArray.optJSONObject(i).optString("zd");
                                        Qutos.buy1 = jsonArray.optJSONObject(i).optString("buy1");
                                        Qutos.buy2 = jsonArray.optJSONObject(i).optString("buy2");
                                        Qutos.position = jsonArray.optJSONObject(i).optString("position");
                                        Qutos.service_charge = jsonArray.optJSONObject(i).optString("service_charge");
                                        mQutoList.add(Qutos);
                                    }
                                    if (quotesAdapter != null) {
                                        quotesAdapter.refresh(mQutoList);
                                    }

                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (detailsTimer != null) {
                detailsTimer.cancel();
            }

        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (detailsTimer != null) {
            detailsTimer.cancel();
        }
        super.onDestroy();
    }
}
